package com.modern.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.modern.mapper.UserMapper;
import com.modern.pojo.LoginInfo;
import com.modern.pojo.PageResult;
import com.modern.pojo.User;
import com.modern.pojo.dto.UserQueryDto;
import com.modern.service.UserService;
import com.modern.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public LoginInfo getLoginInfo(User user) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername())
                .eq(User::getPassword,user.getPassword());
        User loginMessage = userMapper.selectOne(queryWrapper);
        if(loginMessage!=null){
            Map<String,Object> map=new HashMap<>();
            map.put("username",loginMessage.getUsername());
            map.put("id",loginMessage.getId());
            String token = JwtUtil.getToken(map);
            return new LoginInfo(loginMessage.getId(),loginMessage.getUsername(), loginMessage.getName(), loginMessage.getImage(),loginMessage.getPassword(), loginMessage.getCharacterId(),token);
        }
        return null;
    }

    @Override
    public PageResult getByPage(UserQueryDto userQueryDto) {
        PageHelper.startPage(userQueryDto.getPage(),userQueryDto.getPageSize());
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        if(userQueryDto.getName()!=null||userQueryDto.getName()!=""){
            queryWrapper.like(User::getName,userQueryDto.getName());
        }
        if(userQueryDto.getGender()!=null){
            queryWrapper.eq(User::getGender,userQueryDto.getGender());
        }
        List<User> users = userMapper.selectList(queryWrapper);
        Page<User> p=(Page<User>) users;
        return new PageResult(p.getTotal(),p.getResult());
    }

    @Override
    public Integer addUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        return userMapper.insert(user);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public Integer updateUserById(User user) {
        user.setUpdateTime(LocalDateTime.now());
        return userMapper.updateById(user);
    }

    @Override
    public Integer deleteUserByIds(List<Long> ids) {
        return userMapper.deleteByIds(ids);
    }
}
